﻿using Microsoft.EntityFrameworkCore;
using System.Reflection;
using Yitter.IdGenerator;
using NLog.Web;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
using ServiceManagement.Consul;
using B.S.Databasic.Api.Wrter.Common;
using B.S.Databasic.Api.Wrter.AllError;
using B.S.Databasic.Infrastructure;
using B.S.Databasic.Infrastructure.Interface;
using B.S.Databasic.Infrastructure.Inpement;

namespace B.S.Databasic.Api.Wrter.Extensions
{
    public static class ServicesCollectionExtensions
    {
        public static WebApplicationBuilder Inject(this WebApplicationBuilder builder)
        {
            // Add services to the container.
            //全局异常过滤
            builder.Services.AddControllers(x => x.Filters.Add<Globalexceptionfilter>());
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //中文注释
            builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "B.S.Databasic.Api.Wrter.xml", true));
            //注册上下文
            builder.Services.AddDbContext<MyDbContext>(x =>
            {
                x.UseMySql(builder.Configuration.GetConnectionString("db"),new MySqlServerVersion("5.7"));
            });
            //注册中介者
            builder.Services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            //http 上下文
            builder.Services.AddHttpContextAccessor();
            //JWT
            var jwtsettings = builder.Configuration.GetSection("JWT").Get<JwtSettings>();
            //授权认证（使用JWT）
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // 私钥
                var secretByte = Encoding.UTF8.GetBytes(jwtsettings.SigningKey);
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = jwtsettings.Issuer,

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = jwtsettings.Audience,

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });
            
            // 添加授权服务
            builder.Services.AddAuthorization();

            // 配置Swagger
            builder.Services.AddSwaggerGen(o =>
            {
                // 显示 授权信息
                o.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description = "添加JWT授权Token：Bearer Token值",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                o.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[]
            {

            }
        }
    });
            });
            //注册consul
            builder.Configuration.Register();
            //配置Base
            builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            //配置automapper
            builder.Services.AddAutoMapper(typeof(MyAutoMapper));
            //注册雪花id
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions(0));
            //配置日志
            builder.Host.UseNLog();

            return builder;
        }
    //    public static IServiceCollection AddDBContextAccessor<T>(this IServiceCollection services, string ConnectionString, bool enableSqlLog) where T : DbContext
    //    {
    //        return services.AddDbContext<MyDbContext>(x =>
    //        {
    //            x.UseSqlServer(ConnectionString, action =>
    //            {
    //                //配置EFCore重试策略
    //                action.EnableRetryOnFailure(
    //                    maxRetryCount: 10, //最大重试次数
    //                    maxRetryDelay: TimeSpan.FromSeconds(60), //每次重试时间 最大延迟
    //                    errorNumbersToAdd: null); //添加需要重试的错误代码 默认的代码错误为null
    //            })
    //            .EnableSensitiveDataLogging(); //启用敏感日志记录 便于调试 但是注意避免重要信息泄露

    //            if (enableSqlLog)
    //            {
    //                x.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddFilter(
    //                    category: DbLoggerCategory.Database.Name, //类型
    //                    level: LogLevel.Information //日志级别
    //                    ).AddConsole())); //控制台日志
    //            }
    //        });
    //    }
    }
}
